package com.example.qfsx;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.qfsx.bean.LoginResType;
import com.example.qfsx.bean.SharedPreferencesUtil;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Login extends AppCompatActivity {
    Context _this = this;

    private static final String PREFS_NAME = "LoginPrefs"; // SharedPreferences名称
    private static final String KEY_RESPONSE = "response"; // 存储响应的键

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_login);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        Button loginButton = findViewById(R.id.login_button); // 假设按钮的ID为login_button
        loginButton.setOnClickListener(this::getLoginApi); // 设置点击事件
    }

    protected void getLoginApi(View view) {
        EditText usernameObj = findViewById(R.id.mobile);
        EditText passwordObj = findViewById(R.id.code);

        // 获取输入的用户名和密码
        String mobile = usernameObj.getText().toString().trim();
        String code = passwordObj.getText().toString().trim();

        OkHttpClient okHttpClient = new OkHttpClient();
        FormBody form = new FormBody.Builder()
                .add("mobile", mobile)  // 添加手机号到请求体
                .add("code", code)  // 添加验证码到请求体
                .build();
        // 创建一个请求Request
        Request request = new Request.Builder()
                .url("http://123.56.141.187:8001/sms/login")  // 修改1
                .post(form)  // 修改2
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
                runOnUiThread(() -> {
                    Toast.makeText(Login.this, "请求失败", Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                if (response.isSuccessful()) {
                    String responseBody = null;
                    try {
                        if (response.body() != null) {
                            responseBody = response.body().string();
                        }
                        System.out.println("qf123 " + responseBody); // 打印响应


                        // 将数据持久化存储到 SharedPreferences
//                        saveLoginResponseToPreferences(responseBody);
                        SharedPreferencesUtil.saveString(_this,KEY_RESPONSE,responseBody);
                        onJump();
//                        System.out.println("qf123"+userInfo.getData().token);
//                        System.out.println("qf123"+(getLoginResponseFromPreferences() instanceof String));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

//    private void saveLoginResponseToPreferences(String response) {
//        SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
//        SharedPreferences.Editor editor = sharedPreferences.edit();
//        editor.putString(KEY_RESPONSE, response); // 存储响应数据
//        editor.apply(); // 提交更改
//    }

    // 可以在需要时读取数据
//    public  String getLoginResponseFromPreferences() {
//        SharedPreferences sharedPreferences = this.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
//        return sharedPreferences.getString(KEY_RESPONSE, null); // 返回存储的响应数据
//    }
    private void onJump(){
        Gson gson = new Gson();
        LoginResType userInfo = gson.fromJson(SharedPreferencesUtil.getString(_this,KEY_RESPONSE,null), LoginResType.class);
        if(userInfo.getState() == 200){
            Intent intent = new Intent(_this,CartActivity.class);
            startActivity(intent);
        }
    }

}
